﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using EPiServer.Security;

namespace EPiServer.Research.VirtualRoles
{
    public class PageViewRole : VirtualRoleProviderBase
    {
        public string[] Pages { get; set; }

        public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
        {
            base.Initialize(name, config);
            string lst = config["pages"];
            if (!string.IsNullOrEmpty(lst))
            {
                Pages = lst.Split(',');
            }
            VirtualRolesInit vri = new VirtualRolesInit();
            vri.Subscribe(page => HandlePage(page));
        }
        public override bool IsInVirtualRole(System.Security.Principal.IPrincipal principal, object context)
        {
            if (HttpContext.Current == null) return false;
            if (Pages == null) return true;
            if (HttpContext.Current.Session == null) return false;
            if (HttpContext.Current.Session["PageViews"] == null) return false;
            var lst = HttpContext.Current.Session["PageViews"] as List<string>;
            return (bool)(lst.Intersect(Pages).Count() == Pages.Count());

        }

        private void HandlePage(PageBase page)
        {
            if (page.Session["PageViews"] == null)
            {
                page.Session.Add("PageViews", new List<string>());
            }

            var lst = page.Session["PageViews"] as List<string>;

            if (!lst.Contains(page.CurrentPageLink.ToString()))
            {
                lst.Add(page.CurrentPageLink.ToString());
            }
        }
    }
}
